<?php

namespace App\Services;

use App\Repository\Contracts\RoleRepository;
use Symfony\Component\Console\Exception\InvalidArgumentException;

class RoleService
{
    /**
     * @var RoleRepositoryEloquent
     */
    protected $roleRepository;

    public function __construct(RoleRepository $roleRepository)
    {
        $this->roleRepository = $roleRepository;
    }

    /**
     * Get Roles  and paginate.
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getRoles()
    {
        return $this->roleRepository->paginate();
    }

    /**
     * Get one Role  by primary key.
     *
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
     */
    public function getRole($id)
    {
        return $this->roleRepository->find($id);
    }

    /**
     * Create a new line on Role.
     *
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Model|$this
     */
    public function storeRole($data)
    {
        return $this->roleRepository->create($data);
    }

    /**
     * Update Role one line by primary key.
     *
     * @param $id
     * @param array $data
     * @return int
     */
    public function updateRole($id, $data)
    {
        return $this->roleRepository->update($id, $data);
    }

    /**
     * Delete Role one line by primary key.
     *
     * @param $id
     * @return mixed
     */
    public function deleteRole($id)
    {
        return $this->roleRepository->deleteById($id);
    }

    /**
     * 分配权限
     *
     * @param $data
     * @return mixed
     * @throws \Throwable
     */
    public function assignPermissionsToRole($data)
    {
        throw_if(
            !is_array($data['permission_ids']),
            new InvalidArgumentException()
        );

        return $this->roleRepository->assign($data['id'], $data['permission_ids']);
    }

    public function findPermissionsByRoleId($id)
    {
        $role = $this->roleRepository->find($id);

        return $role->permissions;
    }

}